package com.dalei.vds.widget;

import java.io.File;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.View;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;

public class ImageGridViewBinder implements ViewBinder {

	public boolean setViewValue(View view, Object data,
			String textRepresentation) {
		// TODO Auto-generated method stub
		if (view instanceof Checkable) {
			if (data instanceof Boolean) {
				((Checkable) view).setChecked((Boolean) data);
			} else if (view instanceof TextView) {
				// Note: keep the instanceof TextView check at the bottom of
				// these
				// ifs since a lot of views are TextViews (e.g. CheckBoxes).
				((TextView) view).setText(textRepresentation);
			} else {
				throw new IllegalStateException(view.getClass().getName()
						+ " should be bound to a Boolean, not a "
						+ (data == null ? "<unknown type>" : data.getClass()));
			}
		} else if (view instanceof TextView) {
			// Note: keep the instanceof TextView check at the bottom of these
			// ifs since a lot of views are TextViews (e.g. CheckBoxes).
			((TextView) view).setText(textRepresentation);
		} else if (view instanceof ImageView) {
			if (data instanceof Integer) {
				((ImageView) view).setImageResource((Integer) data);
			} else if (data instanceof Drawable) {
				((ImageView) view).setImageDrawable((Drawable) data);
			} else if (data instanceof Bitmap) {
				((ImageView) view).setImageBitmap((Bitmap) data);
			} else if (data instanceof Uri) {
				((ImageView) view).setImageURI((Uri) data);
			} else if (data instanceof File) {
				// Uri uri = Uri.fromFile((File) data);
				// ((ImageView) view).setImageURI(uri);
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inSampleSize = 10;
				Bitmap bitmap = BitmapFactory.decodeFile(
						((File) data).getAbsolutePath(), opts);
				((ImageView) view).setImageBitmap(bitmap);
			} else {
				try {
					((ImageView) view).setImageResource(Integer
							.parseInt(textRepresentation));
				} catch (NumberFormatException e) {
					((ImageView) view).setImageURI(Uri
							.parse(textRepresentation));
				}
			}
		} else {
			throw new IllegalStateException(view.getClass().getName()
					+ " is not a "
					+ " view that can be bounds by this SimpleAdapter");
		}
		return true;
	}

}
